/**
 * 商家管理模块
 */
const express = require('express')
const store = express.Router()

// 导入数据库
const db = require('../../utils/db')

// 导入文件上传解析模块
const getformidable = require('../../utils/myformidable')
const fs = require('fs')

// 导入 ali-oss 上传本地文件
const myoss = require('../../utils/myoss')

// 全局变量
const curNav = 3
const base_path_pic = 'http://admi-yuliner.oss-cn-hangzhou.aliyuncs.com/shoplist/'

// 获取店铺列表
store.get('/storelist', (req, res) => {
   const sql = `SELECT * FROM shoplists ORDER BY id DESC`
   db.query(sql, (err, result) => {
      if (err) throw err
      res.render('Store/storelist', {
         curNav: curNav,
         user: req.session.uname,
         data: result,
         host: base_path_pic
      })
   })
})

// 修改店铺信息
store.get('/storeupdate', (req, res) => {
   const { id } = req.query
   const sql = `SELECT * FROM shoplists WHERE id = ${id}`
   db.query(sql, (err, result) => {
      if (err) throw err
      res.render('Store/storeupdate', {
         curNav: curNav,
         user: req.session.uname,
         data: result[0],
         host: base_path_pic
      })
   })
})
store.post('/storedoupdate', async (req, res) => {
   const { params, files } = await getformidable(req)
   const { shopname, content, fee, id, logo } = params
   const { newFilename, size, filepath } = files.newlogo
   if (size > 0) {
      await myoss.deldata( 'shoplist/' + logo) // 删除远端仓库对应的文件
      const { res: info } = await myoss.pushdata('shoplist/' + newFilename, filepath)// 上传本地文件到远端仓库
      if (info.statusCode === 200 && info.statusMessage.toUpperCase() === 'OK') {
         fs.unlink(filepath, () => { }) // 删除本地logo文件
         // 将数据存入数据库
         const sql = `UPDATE shoplists SET shopname='${shopname}', logo='${newFilename}', content='${content}', fee='${fee}' WHERE id=${id}`
         db.query(sql, (err, result) => {
            if (result.affectedRows > 0) {
               res.send(`<script>alert('更新成功');window.location.href='/store/storelist'</script>`)
            } else {
               res.send(`<script>alert('更新失败');window.location.href='/store/storeupdate?id=${id}'</script>`)
            }
         })
      } else {
         res.send(`<script>alert('更新失败');window.location.href='/store/storeupdate?id=${id}'</script>`)
      }
   } else {
      // 更新数据库的数据
      const sql = `UPDATE shoplists SET shopname='${shopname}', content='${content}', fee='${fee}' WHERE id=${id}`
      db.query(sql, (err, result) => {
         if (result.affectedRows > 0) {
            res.send(`<script>alert('更新成功');window.location.href='/store/storelist'</script>`)
         } else {
            res.send(`<script>alert('更新失败');window.location.href='/store/storeupdate?id=${id}'</script>`)
         }
      })
   }
})

// 商家入驻
store.get('/storeadd', (req, res) => {
   res.render('Store/storeadd', {
      curNav: curNav,
      user: req.session.uname
   })
})
store.post('/storedoadd', async (req, res) => {
   const { params, files } = await getformidable(req)
   const { shopname, content, fee, logo } = params
   const { newFilename, size, filepath } = files.newlogo

   if (size > 0) {
      // 将数据存入数据库
      const sql = `INSERT INTO shoplists(shopname, logo, content, fee) VALUES('${shopname}', '${newFilename}', '${content}', '${fee}')`
      db.query(sql, async (err, result) => {
         if (result.affectedRows > 0) {
            // 上传本地文件到远程仓库
            await myoss.pushdata('shoplist/' +  newFilename, filepath)
            fs.unlinkSync('shoplist/' + filepath) // 删除本地logo文件
            res.send(`<script>alert('入驻成功');window.location.href='/store/storelist'</script>`)
            return
         }
         res.send(`<script>alert('入驻失败');window.location.href='/store/storeadd'</script>`)
      })
   } else {
      // 更新数据库的数据
      const sql = `INSERT INTO shoplists(shopname, logo, content, fee) VALUES('${shopname}', '${logo}', '${content}', '${fee}')`
      db.query(sql, (err, result) => {
         if (result.affectedRows > 0) {
            res.send(`<script>alert('入驻成功');window.location.href='/store/storelist'</script>`)
         } else {
            res.send(`<script>alert('入驻失败');window.location.href='/store/storeadd'</script>`)
         }
      })
   }
})

// 删除店铺
store.get('/storedel', (req, res) => {
   const { id, logo } = req.query
   const sql = `DELETE FROM shoplists WHERE id=${id}`
   db.query(sql, (err, result) => {
      if (result.affectedRows > 0) {
         myoss.deldata('shoplist/' +  logo) // 删除远端对应图片
         res.json({ msg: 'ok' })
      } else {
         res.json({ msg: 'no' })
      }
   })
})

// 搜索功能
store.get('/search', (req, res) => {
   const {kwd} = req.query
   const sql = `SELECT * FROM shoplists`
   db.query(sql, (err, result) => {
      if (result.length > 0) {
         result = result.filter((item) => {
            return item.shopname.includes(kwd) || item.content.includes(kwd)
         })
      }
      res.render('Store/storesearch', {
         curNav: curNav,
         user: req.session.uname,
         data: result,
         host: base_path_pic
      })
   })
 })

module.exports = store